package com.leetcode.Offer;

public class JZ66 {
    public int[] constructArr(int[] a) {
        //用两个数组分别记录从前到后和从后到前的乘积值
        if (a == null || a.length == 0) {
            return new int[]{};
        }
        int[] start = new int[a.length];
        start[0] = a[0];
        int[] end = new int[a.length];
        end[a.length - 1] = a[a.length - 1];

        for (int i = 1; i < a.length; i++) {//从前往后的乘积
            start[i] = a[i] * start[i - 1];
        }
        for (int i = a.length - 2; i >= 0; i--) {//从后往前的乘积
            end[i] = a[i] * end[i + 1];
        }
        int[] rs = new int[a.length];
        for (int i = 0; i < a.length; i++) {
            rs[i] = (i - 1 >= 0 ? start[i - 1] : 1) * (i + 1 < a.length ? end[i + 1] : 1);
        }
        return rs;
    }

    public static void main(String[] args) {
        for (int i : new JZ66().constructArr(new int[]{1, 2, 3, 4, 5})) {
            System.out.print(i + " ");
        }
    }
}
